package lyq.spec.edu.week14_home03;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.Random;


import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MyService extends Service {


    private int temperature;
    private int humidity;
    private static final String TAG = "MyService";

    Random ra = new Random();

    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d("LongRunningService", "executed at " + new Date().
                        toString());
                sendRequestWihtOkhttp();
            }
        }).start();
        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        int anHour =60 * 1000;   // 这是一分钟的毫秒数
        long triggerAtTime = SystemClock.elapsedRealtime() + anHour;
        Intent i = new Intent(MyService.this, MyReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(MyService.this, 0, i, 0);
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 发起网络请求
     */
    private void sendRequestWihtOkhttp() {
        temperature = ra.nextInt(100) + 1;
        humidity = ra.nextInt(100) + 1;

        Log.d(TAG, "温度:"+temperature+"湿度:"+humidity);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    // 构造客户端，相当于浏览器
                    OkHttpClient client = new OkHttpClient();
                    /*RequestBody requestBody = new FormBody().Builder()
                            .add("temperature",temperature)
                            .add("humidity",humidity)
                            .build();*/

                    // 构造请求，相当于在浏览器里输入地址
                    Request request = new Request
                            .Builder()
                            .url("http://www.yyjsx.xyz/api/iot/reportHumiture" + "?temperature=" + String.valueOf(temperature) + "&humidity=" + String.valueOf(humidity))
                            //.post(requestBody)
                            .build();
                    // 发送请求，相当于在浏览器按回车
                    Response response = client.newCall(request).execute();
                    // 更新ListView
                    String body = response.body().string();
                    Log.d(TAG, body);
                    //parseJson(body);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

/*    private void parseJson(String jsonStr) {
        try {
            JSONObject jobj = new JSONObject(jsonStr);
            Log.d(TAG, jobj.getString("success"));

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }*/
}
